"use strict";
/**
 * index controller
 *
 */

import { ObjectId } from 'mongodb';
import { Driver } from "../db";

const utils = require('../utils');

//const webtitle = "江西省地税稽查信息综合管理系统";
const webtitle = "辽宁省地方税务局风险管理系统";

let __dbs: any[];

let getDBs = function () {
    if (__dbs) return __dbs;
    let driver = new Driver();
    __dbs = driver.pagnateSync("dbinfo", {}, 0, 1000);
};

getDBs();

let indexHandler = {
    index: (req: any, res: any): void => {
        let db = req.query.db || __dbs[0].name; // 默认指向第一个库
        let pg = parseInt(req.query.p || 1);
        let limit = parseInt(req.query.l || 20);
        let text = req.query.text || "";
        let src = req.query.source || "全部";
        let day = req.query.day || "0";
        let qurl = "index?l=" + limit;
        let driver = new Driver();
        let condition: any = {};
        if (text != "") {
            condition["title"] = new RegExp(text);
            qurl += "&text=" + encodeURI(text);
        }
        if (src != "" && src != "全部") {
            condition["source"] = src;
        }
        driver.find(db, condition).then((rs: any) => {
            let total = rs.length;
            driver.pagnate(db, condition, (pg - 1) * limit, limit).then((recs: any) => {
                for (let i = 0, j = recs.length; i < j; i++) {
                    let itm = recs[i];
                    if (!itm._create_time) itm._create_time = new Date();
                    itm.create_time = (itm._create_time).Format("yyyy-MM-dd hh:mm");
                    itm.id = itm._id.toHexString();
                }

                //page information build
                let pc = (total + (limit - 1)) / limit;
                let pgs = [];
                let pg_start = 1;
                if (pg > 5) {
                    pg_start = pg - 5;
                }
                let pg_end = pg_start + 10;
                if (pg_end > pc) {
                    pg_end = pc;
                }
                for (let i = pg_start; i <= pg_end; i++) {
                    let pg_item: any = {};
                    pg_item.active = i == pg;
                    pg_item.url = qurl + "&p=" + i + "&db=" + db+"&source="+src;
                    pg_item.text = i;
                    pgs.push(pg_item);
                }

                let dbs = getDBs();
                //page information build end.
                let renderObject: any = {
                    items: recs,
                    text: text,
                    source: src,
                    pgs: pgs,
                    firsturl: qurl + "&p=1&db=" + db+"&source="+src,
                    lasturl: qurl + "&p=" + pc + "&db=" + db+"&source="+src,
                    total: total,
                    day: day,
                    webtitle: webtitle,
                    db: db,
                    dbs: dbs
                };
                renderObject.sources = ["全部"];
                let items = driver.distinct(db, {}, "source").then(
                    (items: any) => {
                        for (let i = 0, j = items.length; i < j; i++) {
                            renderObject.sources.push(items[i]);
                        }
                        res.render("index", renderObject);
                    }, () => { }
                );
            }, (err) => {
                console.error(err);
            });
        }, (error) => {
            console.error(error);
        });
    },

    detail: (req: any, res: any): void => {
        let id = req.query.id;
        let db = req.query.db || "fdcxx";
        let driver = new Driver();
        let recs = driver.find(db, {
            _id: new ObjectId(id)
        }).then((recs: any) => {
            let renderObject: any = {
                id: id,
                items: [],
                text: "没有找到数据",
                db: db,
                webtitle: webtitle
            };
            if (recs.length != 0) {
                let item = recs[0];
                let items: any[] = [];
                for (let k in item) {
                    if (item.hasOwnProperty(k)) {
                        let v = item[k];
                        if (k == "source") {
                            k = "来源";
                        }
                        if (k.startsWith("_") && (k != "_id")) {
                            continue;
                        }
                        if (k == "title") {
                            k = "标题";
                        }
                        if (k == "_id") {
                            k = "ID";
                            v = v.toHexString();
                        }
                        let ii: any = {};
                        ii.name = k;
                        ii.value = v;
                        items.push(ii);
                    }
                }
                renderObject.text = item.title;
                renderObject.items = (<any>items);
            }
            res.render("detail", renderObject);
        }, (err) => {
            console.error(err);
        });
    },

    tianyancha: { // 天眼查数据导入service
        post: (req: any, res: any): void => {
            let jsonStr = req.body;
            let item: any;
            try {
                item = eval(jsonStr);
                if (item.title) {
                    let driver = new Driver();
                    let rs = driver.find(item["_collection"] || "others", {
                        "title": item.title
                    }).then((rs: any) => {
                        if (rs.length > 0) {
                            console.log("item " + item.title + " exists");
                            res.json("{'status':'ok'}");
                        } else {
                            item._create_time = new Date();
                            driver.insert(item["_collection"] || "others", item).then((inserted) => {
                                console.log("item " + item.title + " inserted");
                                res.json("{'status':'ok'}");
                            });
                        };
                    }, (err) => {
                        console.error(err);
                        res.json("{'status':'error'}");
                    });
                } else {
                    console.log("item not parse => " + jsonStr);
                    res.json("{'status':'error'}");
                }
            } catch (e) {
                console.error(e);
                res.json("{'status':'error'}");
            }
            res.end();
        }
    },

    fdcanalysis: (req: any, res: any): void => {
        let driver = new Driver();
        driver.find("ncfdcanaysis", {}).then((recs: any) => {
            let renderObject: any = {
                items: [],
                text: "没有找到数据",
                webtitle: webtitle
            };

            if (recs.length != 0) {
                let items: any[] = [];
                recs.forEach((item: any) => {
                    item["建筑面积"] = parseFloat(item["建筑面积"]).toFixed(2);
                    item["累计销售总价"] = parseFloat(item["累计销售总价"]).toFixed(2);
                    items.push(item);
                });
                renderObject.items = items;
            }
            res.render("analysis", renderObject);
        }, (err) => {
            console.error(err);
        });
    },

    exportanalysis: (req: any, res: any): void => { // 将数据导出到excel中
        let nodeExcel = require('excel-export');
        let conf: any = {};
        conf.cols = [{
            caption: '名称',
            type: 'string'
        }, {
            caption: '发证日期',
            type: 'string'
        }, {
            caption: '销售状态',
            type: 'string'
        }, {
            caption: '户型',
            type: 'string'
        }, {
            caption: '建筑面积',
            type: 'number'
        }, {
            caption: '累计销售总价',
            type: 'number'
        }, {
            caption: '开发商',
            type: 'string'
        }, {
            caption: '项目名称',
            type: 'string'
        }];
        let driver = new Driver();
        driver.find("ncfdcanaysis", {}).then((recs: any) => {
            conf.rows = [];
            recs.forEach((item: any) => {
                let obj: any[] = [];
                obj.push(item.title);
                obj.push(item["发证日期"]);
                obj.push(item["销售状态"]);
                obj.push(item["户型"]);
                obj.push(item["建筑面积"]);
                let xxckdj = item["累计销售总价"];
                if (xxckdj == 'NaN') xxckdj = '';
                obj.push(xxckdj);
                obj.push(item["开发商"]);
                obj.push(item["项目名称"]);
                conf.rows.push(obj);
            });
            let result = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(result, 'binary');
        }, (error) => {
            console.error(error);
        });
    },

    exportData: {
        get: (req: any, res: any): void => {
            let collection = req.query.db || req.query.collection;
            let source=req.query.source||'';
            let driver = new Driver();
            let flag={};
            flag= (source ==''?{}:{"source":source});
            driver.pagnate(collection, flag, 0, 200).then((recs: any) => {
                driver.count(collection, flag).then((cnt) => {
                    let renderObject: any = {
                        items: [],
                        totalCount: 0,
                        text: "没有找到数据",
                        collection: collection,
                        webtitle: webtitle,
                        source:source
                    };
                    if (recs.length != 0) {
                        let items: any[] = [];
                        recs.forEach((item: any) => {
                            item._create_time = item._create_time.toString();
                            items.push(item);
                        });
                        renderObject.items = items;
                        renderObject.totalCount = cnt;
                    }
                    res.render("export.html", renderObject);
                }, (error) => {

                });
            }, () => { });
        },

        post: (req: any, res: any): void => {
            let collection = req.query.db || req.query.collection || 'lnjsgcxxw';
            let source=req.query.source||'';
            source = source ='' ? {}:{"source":source};
            let nodeExcel = require('excel-export');
            let driver = new Driver();
            driver.find(collection, source).then((recs: any) => {
                let conf: any = {};
                let fields: any[] = [];
                conf.cols = [];
                conf.rows = [];
                recs.forEach((rec: any, index: number) => {
                    if (index == 0) {
                        for (var k in rec) {
                            if (rec.hasOwnProperty(k)) {
                                var fld = {
                                    caption: k,
                                    type: 'string'
                                };
                                fields.push(k);
                                conf.cols.push(fld);
                            }
                        }
                    }
                    let obj: any[] = [];
                    fields.forEach((v) => {
                        obj.push(rec[v]);
                    });
                    conf.rows.push(obj);
                });
                let result = nodeExcel.execute(conf);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
                res.end(result, 'binary');
            }, (err) => {
                console.error(err);
            });
        }
    }
};

exports = module.exports = {
    "/": indexHandler.index,
    "/index": indexHandler.index,
    "/detail": indexHandler.detail,
    "/tianyanchaput": indexHandler.tianyancha,
    "/fdcanalysis": indexHandler.fdcanalysis,
    "/exportanalysis": indexHandler.exportanalysis,
    "/exportData": indexHandler.exportData
};